package com.ruigi.control;

import com.ruigi.Exception.Customexception;
import com.ruigi.pojo.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class Commoncontrol {
    @Value("${reggie.path}")
    private String basepath;


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        System.out.println("file!!!!!");

        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID().toString();
        String filename = s + substring;

        File file1 = new File(basepath);
        if (!file1.exists()) {
            //目录不存在，需要创建
            file1.mkdir();
        }

        try {
            file.transferTo(new File(basepath + filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            if (!new File(basepath + name).exists()) {
                throw new Customexception("文件不存在");

            }
            FileInputStream fileInputStream = new FileInputStream(new File(basepath + name));

            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream, outputStream);
            outputStream.flush();

            response.setContentType(MediaType.IMAGE_JPEG_VALUE);


        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
